import * as axios from "axios";
import * as cheerio from "cheerio";
import { Mp4 } from "../models/Mp4";
// const request = axios.default;
const { remote } = require("electron");

const request = axios.default.create({
  // @ts-ignore
  crossDomain: true
});
const API_SEARCH = "http://www.chedvd.com/so.html?k=";

// 查询视频
export async function search(
  text: string
): Promise<{ totalNum: number; list: Mp4[] }> {
  let name = "";
  if (text === "") {
    throw new Error("没有搜索");
  }
  name = text.trim();

  const searchUrl = encodeURI(`${API_SEARCH}${name}`);
  const response = await request.get(searchUrl, {
    headers: {
      Accept:
        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9Accept-Encoding: gzip, deflate",
      Referer: searchUrl
    }
  });
  const document = response.data;

  const list: Mp4[] = [];

  const $ = cheerio.load(document);
  $("tbody")
    .children()
    .each((i, e) => {
      if (i < 1) {
        console.log("表头不需要打印");
        return;
      }
      const video = new Mp4();
      $(e)
        .children()
        .each((ci, ce) => {
          const content = $(ce)
            .text()
            .trim();

          // 歌曲名称
          if (ci === 0) {
            video.name = content;
            const url =
              $(ce)
                .find("a")
                .attr("href") || "";
            // /baling/33.html#m28335
            // href="/song/20588.html"
            if (url.includes("#m")) {
              const id = url.split("#m")[1];
              video.id = id;
            } else {
              const id = (url.match(/song\/(\S*).html/) || [])[1];
              video.id = id;
            }
          }
          // 歌手
          if (ci === 1) {
            video.player = content;
          }
          // 是否可以在线播放
          if (ci === 2) {
            video.onlinePlay = content === "付费";
          }
        });
      list.push(video);
    });

  const pagination: number[] = [];
  // 计算总条数
  $("ul[class=pagination]")
    .children()
    .each((i, e) => {
      const content = $(e)
        .text()
        .trim();
      if (isNumber(content)) {
        pagination.push(Number(content));
      }
    });
  const maxPage: number = pagination.sort((a, b) => b - a)[0] || 0;
  const totalNum = maxPage * 15;
  return { totalNum, list };
}

export async function commonDownload(download_url: string, file_name: string) {
  const response = await request({
    url: download_url,
    method: "GET",
    responseType: "blob" // important
  });
  const url = window.URL.createObjectURL(new Blob([response.data]));
  const link = document.createElement("a");
  link.href = url;
  link.setAttribute("download", file_name);
  document.body.appendChild(link);
  link.click();
}

// 城通下载视频
export async function downloadFromCT(detail_url: string, file_name: string) {
  const response = await request.get(detail_url, {
    headers: {
      Accept:
        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9Accept-Encoding: gzip, deflate",
      Referer: detail_url
    }
  });

  const document = response.data;
  const $ = cheerio.load(document);
  const url = $(".song-down")
    .children("a")
    .eq(0)
    .attr("href");

  console.log("url", url);
  console.log("origin-url", detail_url);
  const main_http = remote.require("./main_http.js");
  const downurl = await main_http.fetchVideo(url);

  console.log("获取到", downurl);
  // 从下载路径中获取下载文件名
  const urlWithoutParam = downurl.split("?")[0];
  const urlBlocks = urlWithoutParam.split("/");
  const filename = unescape(urlBlocks[5]);
  await commonDownload(downurl, filename);
}

function isNumber(val: any) {
  var regPos = /^\d+(\.\d+)?$/; //非负浮点数
  var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
  if (regPos.test(val) || regNeg.test(val)) {
    return true;
  } else {
    return false;
  }
}
